import { Byte } from '../../api/io/Byte';
import { UserExtra } from './UserExtra';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';



/**用户信息属性枚举*/
export const enum E_User {
	/**用户名*/
	ACCOUNT = 0,
	/**渠道*/
	CHANNEL = 1,
	/**密码*/
	PASSWORD = 2,
	/**用户id*/
	USER_ID = 3,
	/**用户额外信息*/
	USER_EXTRA = 4,
	/**枚举数量*/
	EnumCount = 5
}


/**用户信息*/
export class User {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_USER_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_USER_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: User[] = [];

	/**创建入口*/
	public static create(json?: string): User {
		const c = this.POOL.pop() || new User();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**用户名*/
	protected _account: string;
	/**渠道*/
	protected _channel: string;
	/**密码*/
	protected _password: string;
	/**用户id (uint32)*/
	protected _userId: number;
	/**用户额外信息*/
	protected _userExtra: UserExtra = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (User.POOL.indexOf(this) === -1) {
			User.POOL.push(this);
		}
	}

	/**用户名*/
	public get account() {
		return this._account;
	}


	/**用户名*/
	public set account(v: string) {
		this._account = v;
	}


	/**渠道*/
	public get channel() {
		return this._channel;
	}


	/**渠道*/
	public set channel(v: string) {
		this._channel = v;
	}


	/**密码*/
	public get password() {
		return this._password;
	}


	/**密码*/
	public set password(v: string) {
		this._password = v;
	}


	/**用户id*/
	public get userId() {
		return this._userId;
	}


	/**用户id*/
	public set userId(v: number) {
		this._userId = v;
	}


	/**用户额外信息*/
	public get userExtra() {
		return this._userExtra;
	}



	/**通过枚举获取值*/
	public getV(k: E_User): any {
		switch (k) {
			case E_User.ACCOUNT: return this._account;
			case E_User.CHANNEL: return this._channel;
			case E_User.PASSWORD: return this._password;
			case E_User.USER_ID: return this._userId;
			case E_User.USER_EXTRA: return this._userExtra;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_User, v: any): void {
		switch (k) {
			case E_User.ACCOUNT: this._account = v; break;
			case E_User.CHANNEL: this._channel = v; break;
			case E_User.PASSWORD: this._password = v; break;
			case E_User.USER_ID: this._userId = v; break;
			case E_User.USER_EXTRA: this._userExtra = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//用户名
		this._account = '';
		//渠道
		this._channel = '';
		//密码
		this._password = '';
		//用户id
		this._userId = 0;
		//用户额外信息
		if (this._userExtra) {
			this._userExtra.destroy();
			this._userExtra = null;
		}
		if (!fromDestroy) {
			this._userExtra = UserExtra.create();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._account) {
			json.account = this._account;
		}
		if (this._channel) {
			json.channel = this._channel;
		}
		if (this._password) {
			json.password = this._password;
		}
		if (this._userId) {
			json.userId = this._userId;
		}
		if (this._userExtra) {
			json.userExtra = this._userExtra.stringify(false);
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.account) {
			this._account = json.account;
		}
		if (json.channel) {
			this._channel = json.channel;
		}
		if (json.password) {
			this._password = json.password;
		}
		if (json.userId) {
			this._userId = json.userId;
		}
		if (json.userExtra) {
			this._userExtra.destroy();
			this._userExtra = UserExtra.create(json.userExtra);
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeString(this._account);
		byte.writeString(this._channel);
		byte.writeString(this._password);
		byte.writeUint32(this._userId);
		this._userExtra.toBytes(byte);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._account = byte.readString();
		this._channel = byte.readString();
		this._password = byte.readString();
		this._userId = byte.readUint32();
		this._userExtra.fromBytes(byte);
		return this;
	}


	/**克隆*/
	public clone(): User {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = User.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = User.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//用户名
			if (idx === E_User.ACCOUNT) {
				const oldv = this._account;
				this._account = us[i + 1];
				IAsync.dispatch(eventID, idx, this._account, oldv);
				i += 2;
				continue;
			}
			//渠道
			if (idx === E_User.CHANNEL) {
				const oldv = this._channel;
				this._channel = us[i + 1];
				IAsync.dispatch(eventID, idx, this._channel, oldv);
				i += 2;
				continue;
			}
			//密码
			if (idx === E_User.PASSWORD) {
				const oldv = this._password;
				this._password = us[i + 1];
				IAsync.dispatch(eventID, idx, this._password, oldv);
				i += 2;
				continue;
			}
			//用户id
			if (idx === E_User.USER_ID) {
				const oldv = this._userId;
				this._userId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._userId, oldv);
				i += 2;
				continue;
			}
			//用户额外信息
			if (idx === E_User.USER_EXTRA) {
				const fui: string = us[i + 1];
				if (this._userExtra) {
					this._userExtra.processUpdate(fui);
				}
				else {
					console.error('User userExtra is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in User with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: User): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._account !== other._account) {
			updates.push(E_User.ACCOUNT, this._account);
		}
		if (this._channel !== other._channel) {
			updates.push(E_User.CHANNEL, this._channel);
		}
		if (this._password !== other._password) {
			updates.push(E_User.PASSWORD, this._password);
		}
		if (this._userId !== other._userId) {
			updates.push(E_User.USER_ID, this._userId);
		}
		//用户额外信息
		{
			const ui = this._userExtra.getCompareInfo(other._userExtra);
			if (ui && ui.length > 0) {
				updates.push(E_User.USER_EXTRA, ui);
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(User.TOTAL_EVENT_ID, this.getV(0));
	}

}
